package com.nd.android.musicboxlibrary.ui.jaymusicbox.album.details;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.nd.android.musicboxlibrary.GlobalSetting;
import com.nd.android.musicboxlibrary.R;
import com.nd.android.musicboxlibrary.business.bean.Album;
import com.nd.android.musicboxlibrary.business.bean.FileInfo;
import com.nd.android.musicboxlibrary.business.bean.MusicInfo;
import com.nd.android.musicboxlibrary.business.comm.BusProvider;
import com.nd.android.musicboxlibrary.business.comm.MenuPositionEvent;
import com.nd.android.musicboxlibrary.business.comm.NdException;
import com.nd.android.musicboxlibrary.interf.ManagerFactory;
import com.nd.android.musicboxlibrary.ui.adapter.JayMusicSpecialInfoAdapter;
import com.nd.android.musicboxlibrary.ui.common.BaseFragmentActivity;
import com.nd.android.musicboxlibrary.ui.common.ImageLoaderUtil;
import com.nd.android.musicboxlibrary.ui.common.UnMixable;
import com.nd.android.musicboxlibrary.ui.common.ViewInjectorWithReflect;
import com.nd.android.musicboxlibrary.ui.player.PlayerActivity;
import com.nd.android.musicboxlibrary.util.ConfigHelper;
import com.nd.android.musicboxlibrary.util.Log;
import com.nd.android.musicboxlibrary.util.NdTask;
import com.ngds.library.downloadcenter.AppDownloadHelper;
import com.ngds.library.downloadcenter.AppDownloadHelperImpl;
import com.squareup.otto.Subscribe;

import java.util.ArrayList;
import java.util.List;

/**
 * 
 * <br>
 * Created 2014年7月5日 下午4:11:54
 * 
 * @version
 * @author wat.ztag
 * 
 * @see
 */
public class JayMusicSpecialInfoActivity extends BaseFragmentActivity {

    private int lstSum;

    private static final String CLASS_NAME = "jay_special";

    @Override
    public void onResume() {
        super.onResume();
        BusProvider.getInstance().register(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        BusProvider.getInstance().unregister(this);
    }

    /**
     * 
     * <br>
     * Created 2014年9月12日 上午12:04:47
     * 
     * @param event MenuPositionEvent
     * @author wat.ztag
     */
    @Subscribe
    public void selectionByPosition(MenuPositionEvent event) {
        int sum = ConfigHelper.getInstance(this).loadIntKey(
                ConfigHelper.CONFIG_KEY_LIST_SUM + CLASS_NAME, 0);
        if (sum < lstSum) {
            if (holder.lst.getLastVisiblePosition() == event.mPosition) {
                holder.lst.setSelection(holder.lst.getFirstVisiblePosition() + 1);
            } else if (holder.lst.getLastVisiblePosition() - 1 == event.mPosition) {
                // holder.lst.setSelection(holder.lst.getFirstVisiblePosition() + 1);
                Log.i(event.toString());
            }
        } else {
            if (holder.lst.getLastVisiblePosition() == event.mPosition) {
                // holder.lst.setSelection(holder.lst.getFirstVisiblePosition() + 1);
                Log.i(event.toString());
            }
        }
    }

    private ViewHolder holder = new ViewHolder();

    /**
     * 
     * <br>
     * Created 2014年9月12日 上午12:04:52
     * 
     * @version JayMusicSpecialInfoActivity
     * @author wat.ztag
     * 
     * @see
     */
    private class ViewHolder implements UnMixable {
        ListView lst;
        ImageView ivAlbum;
        ImageView ivPlayer;

        /**
         * 
         * <br>
         * Created 2014年10月7日 下午10:08:45
         * 
         * @param list ListView
         * @author wat.ztag
         */
        void setLst(ListView list) {
            this.lst = list;
        }

        /**
         * 
         * <br>
         * Created 2014年10月7日 下午10:08:48
         * 
         * @param iv ImageView
         * @author wat.ztag
         */
        void setIvAlbum(ImageView iv) {
            this.ivAlbum = iv;
        }

        /**
         * 
         * <br>
         * Created 2014年10月7日 下午10:08:51
         * 
         * @param player ImageView
         * @author wat.ztag
         */
        void setIvPlayer(ImageView player) {
            this.ivPlayer = player;
        }

    }

    private JayMusicSpecialInfoAdapter mSingleAdapter;

    private List<MusicInfo> singles = new ArrayList<MusicInfo>();

    private Album album;

    private DownloadReceiver mDownloadReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mbx_jay_music_special_info_activity);
        ViewInjectorWithReflect.injectView(holder, this);
        initData();
        setupView();
        addListeners();

        mDownloadReceiver = new DownloadReceiver();
        registerReceiver(mDownloadReceiver, new IntentFilter(
                AppDownloadHelper.ACTION_DOWNLOAD_COMPLETE));

        if (album != null) {
            new GetMusicListOfAlbum(this, R.string.mbx_runing).executeByVersion();
        }
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(mDownloadReceiver);
        super.onDestroy();
    }

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:53:28
     * 
     * @author wat.ztag
     */
    protected void initData() {
        Intent intent = getIntent();
        if (intent != null) {
            String params = intent.getStringExtra(GlobalSetting.PARAMS_JSON);
            if (!TextUtils.isEmpty(params)) {
                album = new Gson().fromJson(params, Album.class);
            }
        }
    }

    /**
     * 
     * <br>
     * Created 2014年9月12日 上午12:04:55
     * 
     * @author wat.ztag
     */
    private void setupView() {
        setRightButton(R.drawable.mbx_btn_close_selector);
        mSingleAdapter = new JayMusicSpecialInfoAdapter(this);
        mSingleAdapter.setDatas(singles);
        holder.lst.setAdapter(mSingleAdapter);
        if (album != null) {
            if (!TextUtils.isEmpty(album.getName())) {
                txtTitle.setText(album.getName());
            }
            ImageLoaderUtil.displayPic(album.getImgUrl(GlobalSetting.MUSIC_IMAGE_SIZE),
                    holder.ivAlbum);
        }
    }

    /**
     * 
     * <br>
     * Created 2014年9月12日 上午12:04:59
     * 
     * @author wat.ztag
     */
    private void addListeners() {
        holder.lst.setOnItemClickListener(mSingleAdapter);
        holder.ivPlayer.setOnClickListener(this);

        holder.lst.setOnScrollListener(new OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView arg0, int arg1) {
            }

            @Override
            public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
                lstSum = arg2;
                int sum = ConfigHelper.getInstance(getApplicationContext()).loadIntKey(
                        ConfigHelper.CONFIG_KEY_LIST_SUM + CLASS_NAME, arg2 + 1);
                if (arg2 < sum && arg2 != 0) {
                    ConfigHelper.getInstance(getApplicationContext()).saveIntKey(
                            ConfigHelper.CONFIG_KEY_LIST_SUM + CLASS_NAME, arg2);
                }
            }
        });
    }

    /**
     * 
     * <br>
     * Created 2014年9月12日 上午12:05:03
     * 
     * @version JayMusicSpecialInfoActivity
     * @author wat.ztag
     * 
     * @see
     */
    private class GetMusicListOfAlbum extends NdTask {

        /**
         * Creates a new instance of GetMusicListOfAlbum. <br>
         * Created 2014年9月12日 上午12:05:08
         * 
         * @param context Context
         * @param resId int
         */
        public GetMusicListOfAlbum(Context context, int resId) {
            super(context, resId);
        }

        @Override
        protected void doSuccess(Object result) {
            if (result != null) {
                singles = (List<MusicInfo>) result;
                mSingleAdapter.setDatas(singles);
            }
        }

        @Override
        protected void doFail(NdException result) {
            Toast.makeText(mContext, result.getSimpleMsg(), Toast.LENGTH_LONG).show();
        }

        @Override
        protected Object doInBackground(Object... arg0) {
            return ManagerFactory.getPlaylistInstance(getApplicationContext()).getMusicListOfAlbum(
                    album.getId());
        }
    }

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:34:14
     * 
     * @version JayMusicSpecialInfoActivity
     * @author wat.ztag
     * 
     * @see
     */
    public class DownloadReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (AppDownloadHelper.ACTION_DOWNLOAD_COMPLETE.equals(action) && album != null) {

                try {
                    long downloadId = intent.getLongExtra(AppDownloadHelper.EXTRA_DOWNLOAD_ID, 0);
                    String url = intent.getStringExtra(AppDownloadHelper.EXTRA_DOWNLOAD_URI);
                    AppDownloadHelper appDownloadHelperImpl = AppDownloadHelperImpl
                            .getInstance(getApplicationContext());
                    if (!TextUtils.isEmpty(appDownloadHelperImpl.getFileName(downloadId))) {
                        String description = appDownloadHelperImpl.getDescription(context, url);
                        FileInfo fileInfo = new Gson().fromJson(description, FileInfo.class);
                        if (fileInfo != null &&  (fileInfo.getType() == FileInfo.TYPE_MUSIC 
                        		|| fileInfo.getType() == FileInfo.TYPE_HQ_MUSIC)) {
                        	//by jiangwb
                            new GetMusicListOfAlbum(JayMusicSpecialInfoActivity.this,
                                    R.string.mbx_runing).executeByVersion();
                        }
                    }
                } catch (Exception e) {
                    Log.d("DownloadSuccessReceiver Ablum");
                }
            }
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();

        if (id == R.id.btnRight) {
            PlayerActivity.removeSubActivity();
            finish();

        } else if (id == R.id.ivPlayer) {
            if (singles != null && singles.size() > 0) {
                ManagerFactory.getPlayerInstance().playBySpecialItem(this, singles.get(0),
                    (ArrayList<MusicInfo>) singles);
            } else {
                Toast.makeText(this, "没有歌曲", Toast.LENGTH_LONG).show();
            }

        }

        super.onClick(v);
    }
}
